{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8f933896",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2023-02-08T13:37:58.615149Z",
     "start_time": "2023-02-08T13:37:55.445721Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "import torch\n",
    "import random\n",
    "import glob\n",
    "import os\n",
    "from rich.progress import track\n",
    "\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bffaa19e",
   "metadata": {},
   "source": [
    "## Poisson"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f108d010",
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_poisson_noise(img, scale=1.0, gray_noise=False):\n",
    "    \"\"\"Generate poisson noise.\n",
    "    Ref: https://github.com/scikit-image/scikit-image/blob/main/skimage/util/noise.py#L37-L219\n",
    "    Args:\n",
    "        img (Numpy array): Input image, shape (h, w, c), range [0, 1], float32.\n",
    "        scale (float): Noise scale. Default: 1.0.\n",
    "        gray_noise (bool): Whether generate gray noise. Default: False.\n",
    "    Returns:\n",
    "        (Numpy array): Returned noisy image, shape (h, w, c), range[0, 1],\n",
    "            float32.\n",
    "    \"\"\"\n",
    "    if gray_noise:\n",
    "        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "    # round and clip image for counting vals correctly\n",
    "    img = np.clip((img * 255.0).round(), 0, 255) / 255.\n",
    "    vals = len(np.unique(img))\n",
    "    vals = 2**np.ceil(np.log2(vals))\n",
    "    out = np.float32(np.random.poisson(img * vals) / float(vals))\n",
    "    noise = out - img\n",
    "    if gray_noise:\n",
    "        noise = np.repeat(noise[:, :, np.newaxis], 3, axis=2)\n",
    "    return noise * scale\n",
    "\n",
    "\n",
    "def add_poisson_noise(img, scale=1.0, clip=True, rounds=False, gray_noise=False):\n",
    "    \"\"\"Add poisson noise.\n",
    "    Args:\n",
    "        img (Numpy array): Input image, shape (h, w, c), range [0, 1], float32.\n",
    "        scale (float): Noise scale. Default: 1.0.\n",
    "        gray_noise (bool): Whether generate gray noise. Default: False.\n",
    "    Returns:\n",
    "        (Numpy array): Returned noisy image, shape (h, w, c), range[0, 1],\n",
    "            float32.\n",
    "    \"\"\"\n",
    "    noise = generate_poisson_noise(img, scale, gray_noise)\n",
    "    out = img + noise\n",
    "    if clip and rounds:\n",
    "        out = np.clip((out * 255.0).round(), 0, 255) / 255.\n",
    "    elif clip:\n",
    "        out = np.clip(out, 0, 1)\n",
    "    elif rounds:\n",
    "        out = (out * 255.0).round() / 255.\n",
    "    return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de404ff2",
   "metadata": {},
   "outputs": [],
   "source": [
    "HR_path = './kodak24/HR/'\n",
    "LR_path = './kodak24/kodak24_poisson_20/'\n",
    "id_img_paths = glob.glob(os.path.join(HR_path, '*.jpg')) + \\\n",
    "               glob.glob(os.path.join(HR_path, '*.png'))\n",
    "\n",
    "scale = 2\n",
    "for i in track(id_img_paths):\n",
    "    out_path = LR_path + i.split('/')[-1].split('.')[0] + '.png'\n",
    "    img = cv2.imread(i)    \n",
    "    out = add_poisson_noise(img/255., scale=scale)*255.\n",
    "    cv2.imwrite(out_path, out)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b113b15",
   "metadata": {},
   "source": [
    "## Gaussian"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "46a1e819",
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_Gaussian_noise_color(img, noise_level=15):\n",
    "    img += np.random.normal(0, noise_level/255.0, img.shape).astype(np.float32)\n",
    "    img = np.clip(img, 0.0, 1.0)\n",
    "    return img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b253ad7",
   "metadata": {},
   "outputs": [],
   "source": [
    "HR_path = './urban100/HR/'\n",
    "LR_path = './urban100/urban100_g_15/'\n",
    "id_img_paths = glob.glob(os.path.join(HR_path, '*.jpg')) + \\\n",
    "               glob.glob(os.path.join(HR_path, '*.png'))\n",
    "\n",
    "noise_level = 15\n",
    "for i in track(id_img_paths):\n",
    "    out_path = LR_path + i.split('/')[-1].split('.')[0] + '.png'\n",
    "    img = cv2.imread(i)    \n",
    "    out = add_Gaussian_noise_color(img/255., noise_level=noise_level)*255.\n",
    "    cv2.imwrite(out_path, out)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5406dea2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c942fb0",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b53ad6ec",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
